﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ButtonSFX : MonoBehaviour {

    [SerializeField]
    AudioClip clip;
    public AudioClip publicClip { get { return clip; } set { clip = value; } }

    const float Interval = 0.5f;

    Button m_Button;
    Toggle m_Toggle;

    bool InBlock = false;//是否在屏蔽期间
    // Use this for initialization
    private void Awake()
    {
        LoadAudio();
    }

    public void LoadAudio()
    {
        if (clip == null)
            clip = ResourceManager.LoadUIAudio(Audio.btn_common);
    }

    void Start()
    {
        m_Button = gameObject.GetComponent<Button>();
        if (m_Button != null)
        {
            m_Button.onClick.AddListener(OnClick);
        }

        m_Toggle = gameObject.GetComponent<Toggle>();
        if (m_Toggle != null)
        {
            m_Toggle.onValueChanged.AddListener(OnToggleChanged);
        }
    }

    /// <summary>
    /// 屏蔽期间刚好被隐藏
    /// </summary>
    void OnEnable()
    {
        if (InBlock)
        {
            InBlock = false;

            if(m_Button)
                m_Button.interactable = true;

            if (m_Toggle)
                m_Toggle.interactable = true;
        }
    }


    void OnClick()
    {
        if (m_Button != null)
        {
            InBlock = true;
            m_Button.interactable = false;
            Invoke("OnReset", Interval);

            AudioController.instance.Play(clip);
        }
    }

    void OnReset()
    {
        InBlock = false;

        if (m_Button != null)
            m_Button.interactable = true;

        if (m_Toggle != null)
            m_Toggle.interactable = true;
    }


    void OnToggleChanged(bool isOn)
    {
        if (m_Toggle != null && isOn)
        {
            InBlock = true;
            m_Toggle.interactable = false;
            Invoke("OnReset", Interval);

            AudioController.instance.Play(clip);
        }
    }
}
